package petertel.pbx.utils;

import petertel.pbx.connector.Executor;

public class Parser {

	public static void main(String[] args) {
		Node root = parseFile("/etc/asterisk/logger.conf");
		System.out.println(root);
	}

	private static Node parseFile(String filename) {
		String[] lines = ParserUtils.readFile2(new Executor(), filename);
		Node node = new Node();
		int start = -1, end = 0;
		for (; end < lines.length; end++) {
			String line = lines[end];
			if (!ParserUtils.isSection(line)) {
				continue;
			}
			if (start >= 0 && start < end) {
				Node child = parseSection(lines, start, end);
				node.appendChild(child);
			}
			start = end;
		}
		Node child = parseSection(lines, start, end);
		node.appendChild(child);
		return node;
	}

	private static Node parseSection(String[] lines, int start, int end) {
		Node node = new Node();
		node.setLineno(start);
		node.setLine(lines[start]);
		for (int i = start + 1; i < end; i++) {
			String line = lines[i];
			if (line.trim().equals("")) {
				continue;
			}
			if (ParserUtils.isComment(line)) {
				continue;
			}
			if (!ParserUtils.isPair(line)) {
				throw new RuntimeException("Unknow format: " + line);
			}
			Node child = new Node();
			child.setLineno(i);
			child.setLine(lines[i]);
			node.appendChild(child);
		}
		return node;
	}
}
